##########################################################################################

library(data.table)
library(optparse)
library(parallel)
library(dplyr)
library(RColorBrewer)
library(ggplot2)
library(ggsci)
library(ggpubr)

##########################################################################################

option_list <- list(
    make_option(c("--sample_list_file"), type = "character"),
    make_option(c("--ddr_file"), type = "character"),
    make_option(c("--rsem_file_forcor"), type = "character"),
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
    sample_list_file <- "~/20220915_gastric_multiple/rna_batch1/analysis/config/tumor_normal.list"
    ddr_file <- "~/20220915_gastric_multiple/rna_batch1/analysis/images/ddr_gsva/gsva_ddr.MutipleStage.tsv"
    rsem_file_forcor <- "~/20220915_gastric_multiple/rna_batch1/analysis/RSEM/CombineTpm.FilterLowExpression-MergeMutiSample.tsv"
    out_path <- "~/20220915_gastric_multiple/rna_batch1/analysis/images/ddr_gsva"

}

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

sample_list_file <- opt$sample_list_file
rsem_file_forcor <- opt$rsem_file_forcor
ddr_file <- opt$ddr_file
out_path <- opt$out_path

dir.create(out_path , recursive = T)

##########################################################################################

result <- data.frame(fread(ddr_file))
dat_tpm_useExpression <- data.frame(fread(rsem_file_forcor))

##########################################################################################

result <- subset(result , CellType=="All_DDR")

##########################################################################################
## 评估基因表达和干细胞评分的关系
dat_stemscore <- data.frame(stem_score = result$Ratio , ID = paste0(result$Sample , "_" , result$Class))

dat_cor <- c()
for( gene in dat_tpm_useExpression$Hugo_Symbol ){
    print(gene)
    tmp_tpm <- subset( dat_tpm_useExpression , Hugo_Symbol == gene )
    tmp_tpm <- t(tmp_tpm[,-c(1:2)])
    colnames(tmp_tpm) <- "TPM"
    tmp_tpm <- data.frame(tmp_tpm)
    tmp_tpm$ID <- rownames(tmp_tpm)

    tmp_tpm <- merge(tmp_tpm , dat_stemscore , by = "ID" )
    tmp_tpm$Hugo_Symbol <- gene

    cor <- as.numeric(cor.test( tmp_tpm$TPM , tmp_tpm$stem_score , method = "spearman" )$estimate)
    p <- as.numeric(cor.test( tmp_tpm$TPM , tmp_tpm$stem_score , method = "spearman"  )$p.value)

    tmp_dat <- data.frame( Hugo_Symbol = gene , cor = cor , p = p  )

    dat_cor <- rbind( dat_cor , tmp_dat )
}

out_name <- paste0( out_path , "/DDRScore_Expression.tsv" )
dat_cor$q <- p.adjust( dat_cor$p , method  = "fdr" )
write.table( dat_cor , out_name , row.names = F , quote = F , sep = "\t" )